import VueI18n from 'vue-i18n';
import Util from './util.js';
import spe from '../../assets/lang/calendar/speNationalList';
import getLang from '../../assets/lang/mergeLang';

const i18n = new VueI18n({
  locale: JE.getCookies('je-local-lang') || 'zh_CN', // 语言标识
  messages: {
    // eslint-disable-next-line camelcase
    zh_CN: getLang('zh', [{ name: '_calendar', data: require('./../../assets/lang/calendar/zh') }]), // 中文语言包
    en: getLang('en', [{ name: '_calendar', data: require('./../../assets/lang/calendar/en') }]), // 英文语言包
  },
});


export default {
  i18n,
  data() {
    return {
      rendered: false,
      currentDate: new Date(), // 当前日期
      selectDate: new Date(), // 选中日期
      collapseDays: true, // 默认折叠
      tasks: {}, // 日程数据
      currentTasks: [], // 选中日期日程
      weekHeader: ['一', '二', '三', '四', '五', '六', '日'],
      lang: JE.getCookies('je-local-lang') || 'zh_CN',
    };
  },
  computed: {
    currentMonth() {
      return Ext.Date.format(this.currentDate, 'Y年m月');
    },
    days() {
      return this.getDays();
    },
    showList() {
      const currentDate = Ext.Date.format(this.currentDate, 'Y-m-d');
      const selectDate = Ext.Date.format(this.selectDate, 'Y-m-d');
      if (currentDate.split('-')[0] === selectDate.split('-')[0]
        && currentDate.split('-')[1] === selectDate.split('-')[1]) {
        return true;
      }
      return false;
    },
  },
  mounted() {
    const me = this;
    me.$nextTick(() => {
      const day = { sDate: Ext.Date.format(me.selectDate, 'Y-m-d') };
      me.selectDay(day);
      me.rendered = true;
    });
  },
  methods: {
    _initCtr() {
      JE.initCtr('JE.sys.calendar.controller.CalendarController');
    },
    /**
    * 任务标记
    * @param {Object} day day
    * @returns {*}
    */
    isTask(day) {
      return JE.isNotEmpty(this.tasks[day.sDate]);
    },
    /**
    * 选中标记
    * @param {*} day day
    * @returns {*}
    */
    isSelect(day) {
      return day.sDate == Ext.Date.format(this.selectDate, 'Y-m-d');
    },
    /**
     * 选中周标记
     * @param {*} week week
     * @returns {*}
     */
    isSelectWeek(week) {
      const dayStr = Ext.Date.format(this.selectDate, 'Y-m-d');
      let select = false;
      for (let i = 0; i < week.length; i++) {
        if (week[i].sDate == dayStr) {
          select = true;
          break;
        }
      }
      return select;
    },
    /**
     * 选中日期
     * @param {*} day *
     */
    selectDay(day) {
      this.selectDate = Ext.Date.parse(day.sDate, 'Y-m-d');
      this.currentTasks = this.tasks[day.sDate] || [];
      if (day.prevMonth) {
        this.prevMonth();
      } else if (day.nextMonth) {
        this.nextMonth();
      }
    },
    /**
     * 今天
     */
    today() {
      this.currentDate = this.selectDate = new Date();
      this.collapseDays = false;
      const me = this;
      me.$nextTick(() => {
        // 选中日期
        const day = { sDate: Ext.Date.format(me.selectDate, 'Y-m-d') };
        me.selectDay(day);
      });
    },
    /**
     * 下月
     */
    nextMonth() {
      this.currentDate = Ext.Date.subtract(this.currentDate, Ext.Date.MONTH, -1);
      this.collapseDays = false;
    },
    /**
     * 上月
     */
    prevMonth() {
      this.currentDate = Ext.Date.subtract(this.currentDate, Ext.Date.MONTH, 1);
      this.collapseDays = false;
    },
    /**
     * 获得当前月的所有日期
     * @returns {*}
     */
    getDays() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      const weeks = Util.calendarWeeks(year, month);
      this.initTasks(weeks);
      return weeks;
    },
    /**
     * 获得当前月的日程
     * @param {*} weeks 9
     */
    initTasks(weeks) {
      const me = this;
      const startDate = weeks[0][0].sDate;
      const endDate = weeks[weeks.length - 1][6].sDate;
      const params = {
        tableCode: 'JE_SYS_CALENDAR',
        limit: -1,
        permSql: `AND (SY_CREATEUSER='${JE.currentUser.userCode}' OR CALENDAR_GROUPID IN 
        (SELECT GROUPUSER_GROUP_ID FROM JE_SYS_GROUPUSER WHERE GROUPUSER_USERID='${JE.currentUser.userId}') 
        OR CALENDAR_GROUPID IN (SELECT JE_SYS_CALENDARGROUP_ID FROM JE_SYS_CALENDARGROUP WHERE 
          SY_CREATEUSER='${JE.currentUser.userCode}'))`,
        whereSql: `AND ((CALENDAR_STARTTIME>='${startDate}' AND CALENDAR_STARTTIME<='${endDate}') 
        or (CALENDAR_ENDTIME>='${startDate}' AND CALENDAR_ENDTIME<='${endDate}') or 
        (CALENDAR_STARTTIME<='${startDate}' AND CALENDAR_ENDTIME>='${endDate}'))`,
      };
      JE.ajax({
        url: JE.getUrlMaps('je.core.calendar', 'load'),
        params,
        async: true,
        success(response) {
          const tasks = JE.getAjaxData(response).rows;
          const taskObj = {};
          Ext.each(tasks, (task) => {
            let format = 'Y-m-d';
            // 判空
            if (JE.isEmpty(task.CALENDAR_STARTTIME) || JE.isEmpty(task.CALENDAR_ENDTIME)) {
              return false;
            }
            // 如果数据库存的长度大于11，则说明是带时分秒的
            if (task.CALENDAR_STARTTIME.length > 11 && task.CALENDAR_ENDTIME.length > 11) {
              format = 'Y-m-d H:i:s';
            }

            const startDate1 = Ext.Date.clearTime(Ext.Date.parse(task.CALENDAR_STARTTIME, format));
            const endDate1 = Ext.Date.clearTime(Ext.Date.parse(task.CALENDAR_ENDTIME, format));
            // 计算任务周期
            const days = JE.DATE.diffDays(startDate1, endDate1);

            // 为每一天增加任务新
            for (let i = 0; i <= days; i++) {
              const dateStr = Ext.Date.format(startDate1, 'Y-m-d');
              taskObj[dateStr] = taskObj[dateStr] || [];
              taskObj[dateStr].push(task);

              startDate1.setDate(startDate1.getDate() + 1);
            }
          });
          me.tasks = taskObj;
          if (me.selectDate) {
            me.currentTasks = me.tasks[Ext.Date.format(me.selectDate, 'Y-m-d')];
          }
        },
      }).rows;
    },
    /**
     * 打开日程
     */
    showCal() {
      const me = this;
      me._initCtr();
      const win = JE.win({
        title: me.$i18n.locale == 'zh_CN' ? '日程' : 'Schedule',
        autoShow: true,
        items: [{
          xtype: 'calendar.mainview',

        }],
      });
      win.on('close', () => {
        me.initTasks(me.days);
      });
    },
    /**
     * 编辑日程
     * @param {*} task 1
     * @param {*} index 1
     */
    editCal(task) {
      const me = this;
      // 获取系统变量配置的 日历表单功能code
      const funcCode = JE.systemConfig && JE.systemConfig.CALENDAR_FUNCCODE;
      // 点击创建
      if (!task) {
        if (!funcCode) {
          me.createDefWin();
        } else {
          const win = JE.showFunc(funcCode, {
            type: 'form',
          });
          win.on('close', () => {
            me.initTasks(me.days);
          });
        }
      } else {
        me.openFuncWin(task);
      }
    },
    // 创建默认日历新建表单窗口
    createDefWin(task) {
      const me = this;
      const selectDate = Ext.Date.format(me.selectDate, 'Y-m-d H:i:s');
      me._initCtr();
      const win = Ext.create('JE.sys.calendar.form.EventWindow', {
        selectDate,
        callback() {
          me.initTasks(me.days);
        },
        autoShow: true,
      });
      // 如果有task  则回显
      if (task) {
        const form = win.down('panel[xtype=form]');
        form.form.setValues(task);
      }
    },
    // 打开功能表单窗口
    openFuncWin(task) {
      const me = this;
      const config = task.CALENDAR_CONFIG ? Ext.decode(task.CALENDAR_CONFIG) : {};
      if (config.funcCode) {
        const win = JE.showFunc(config.funcCode, {
          type: 'form',
          id: config.pkValue,
        });
        win.on('close', () => {
          me.initTasks(me.days);
        });
      } else {
        me.createDefWin(task);
      }
    },
    getYearEn(cn) {
      if (!cn) return;
      if (this.$i18n.locale == 'zh_CN') return cn;
      return cn.replace('年', '/').replace('月', '');
    },
    getEn(cn) {
      if (!cn) return;
      if (this.$i18n.locale == 'zh_CN') return cn;
      return spe[cn] || cn;
    },
  },
};
